<template>
  <div style="height: calc(100vh - 90px)">
    <!--  -->
    <crumbs @goBack="() => {}" :superiorMenu="['生产报表']" currentMenu="逾期统计" style="margin-bottom: 12px">
      <span slot="content">
        <div class="topSearch">
          <a-form-model ref="ruleForm" layout="inline" :model="filterForm">
            <a-form-model-item label="计划完成日期">
              <a-range-picker
                :allowClear="true"
                v-model="dateForm['planEndTime']"
                style="width: 100%"
                :disabled-date="disabledDate"
                @change="(v) => onOk(v)"
              />
            </a-form-model-item>
            <a-button @click="handleShowFilter" style="margin-top: 4px" icon="filter"
              >筛选 <span class="filter-num" style="margin-left: 5px">{{ ' ' + filteredNums }}</span></a-button
            >
          </a-form-model>
        </div>
      </span>
    </crumbs>
    <div  style="height: calc(100vh - 264px);overflow:scroll">
      <!-- 头部模块 -->
      <a-card :bordered="false">
        <div class="topBox">
          <div style="width: 100%; display: flex; justify-content: space-between">
            <div id="barchart" style="width: 50%; height: 200px; border-right: 1px solid #eee"></div>
            <div id="piechart" style="width: 50%; height: 200px"></div>
          </div>
        </div>
        <span style="position: absolute; right: 20px; top: 20px" class="btn-text" @click="reasonShow"
          ><a-icon type="setting" /> 逾期原因</span
        >
      </a-card>
      <div style="height: 12px; background: #f0f2f5"></div>
      <!-- 逾期原因弹窗 -->
      <a-modal v-model="reasonVisibles" title="配置逾期原因项" @ok="handleOk" @cancel="cancelReason">
        <a-table :columns="reasonColumns" :data-source="reasonList" :pagination="false" :scroll="{ y: '400px' }">
          <span slot="serialNo" slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span slot="overdueReason" slot-scope="text, record">
            <a-input placeholder="请输入" v-model="record.overdueReason" :maxLength="15" />
          </span>
          <span slot="actions" slot-scope="text, record, index">
            <span class="btn-text" @click="delReason(record, index)">删除</span>
          </span>
        </a-table>
        <div class="btn-text" style="text-align: center; padding-top: 24px" @click="addReason">+ 新增逾期原因</div>
      </a-modal>
      <a-card :bordered="false">
        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <a-button @click="showColumn" icon="unordered-list" style="margin-right: 10px"> 设置列 </a-button>
          <a-button @click="refresh" type="primary" style="float: right" icon="sync">更新</a-button>
          <a-button @click="handleExport(selectedRows)" type="primary" style="float: right" icon="upload">导出</a-button>
        </div>
        <div>
          <a-table
            row-key="id"
            size="middle"
            :key="tableKey"
            :scroll="{ x: scrollX, y: 'calc(100vh - 348px)' }"
            :hideDefaultSelections="false"
            :columns="columns"
            :dataSource="modelList"
            :pagination="false"
            @change="tableChange"
            :row-selection="{ selectedRowKeys: selectedRowKeys, columnTitle: ' ', onChange: onSelectChange }"
            class="j-table-force-nowrap"
            :loading="loadingTable"
            :components="drag(columns, 'OVERDUE_STATISTICS')"
          >
            <!-- 行信息 -->
            <span
              slot="orderCode"
              :title="record.orderCode"
              slot-scope="text, record"
              class="btn-text"
              @click="handleDetail(record.id, '/workOrderDetail', '/productionReport/overdueStatistics')"
            >
              {{ record.orderCode }}
            </span>
            <span slot="overdueDay" :title="text" slot-scope="text" :style="{ color: text > 0 ? 'red' : '' }">
              {{ text }}
            </span>
            <span slot="overdueReason" slot-scope="text, record">
              <!-- {{ record.overdueReason }} -->
              <a-select
                placeholder="请选择"
                allowClear
                style="width: 100%"
                v-model="record.overdueReasonId"
                @change="(e) => changeReason(e, record)"
              >
                <a-select-option :title="item.overdueReason" v-for="(item, i) in reasonList" :key="i" :value="item.id">{{
                  item.overdueReason
                }}</a-select-option>
              </a-select>
            </span>
            <span slot="planEndTime" slot-scope="text">
              {{ moment(text).format('YYYY-MM-DD HH:mm') }}
            </span>
            <!-- 输入框搜索 -->
            <div slot="searchInput" slot-scope="{ selectedKeys, confirm, clearFilters, column }" class="searchWorkOreder">
              <a-input
                placeholder="请输入"
                v-model="filterForm[column.dataIndex]"
                style="width: 188px; display: block"
                @pressEnter="handleSearch"
              />
              <a-button
                type="primary"
                style="width: 80px; margin-left: 20px; display: block"
                @click="() => handleSearch(selectedKeys, confirm, column.dataIndex, clearFilters)"
              >
                搜索
              </a-button>
            </div>
            <a-icon
              slot="searchIcon"
              slot-scope="filtered"
              type="search"
              :style="{ color: filtered ? '#108ee9' : undefined }"
            />
            <!-- 选择搜索 -->
            <div slot="selectDropdown" slot-scope="{ confirm, clearFilters, column }" class="searchWorkOreder">
              <a-select
                mode="multiple"
                placeholder="请选择"
                allowClear
                style="width: 188px"
                v-model="filterForm[column.searchKey]"
              >
                <a-select-option v-for="(item, i) in typeList" :key="i" :value="item.value">{{
                  item.text
                }}</a-select-option>
              </a-select>
              <a-button
                type="primary"
                style="width: 80px; margin-left: 20px; display: block"
                @click="() => handleSearch(confirm, column.searchKey, clearFilters)"
              >
                搜索
              </a-button>
            </div>
            <!-- 生产状态选择搜索 -->
            <div slot="selectDropdownStatus" slot-scope="{ confirm, clearFilters, column }" class="searchWorkOreder">
              <a-select
                mode="multiple"
                placeholder="请选择"
                allowClear
                style="width: 188px"
                v-model="filterForm[column.searchKey]"
              >
                <a-select-option v-for="(item, i) in statusList" :key="i" :value="item.value">{{
                  item.label
                }}</a-select-option>
              </a-select>
              <a-button
                type="primary"
                style="width: 80px; margin-left: 20px; display: block"
                @click="() => handleSearch(confirm, column.searchKey, clearFilters)"
              >
                搜索
              </a-button>
            </div>
            <a-icon
              slot="selectIcon"
              slot-scope="filtered"
              type="filter"
              :style="{ color: filtered ? '#108ee9' : undefined }"
            />
          </a-table>
        </div>
        <SetColumn
          columnName="设置列"
          ref="SetColumn"
          v-if="showSetColumn"
          @sureBtn="sureBtn"
          @cancelBtn="showSetColumn = false"
        />
      </a-card>
    </div>
    <a-drawer placement="right" width="500" :visible="showFilter" @close="closeFilter">
      <div class="filter-body">
        <div slot="title" class="uni-card filter-tit">
          筛选 <span class="filter-num">{{ filteredNums }}</span>
        </div>
        <div class="uni-card" v-if="filteredNums > 0" style="background: #fff">
          <div v-for="(item, i) in filteredList" :key="i" v-show="item.text" class="tag-wrap">
            <span class="filter-tag" @click="delFiltered(item.key)">
              <span class="tag-text">{{ `${item.title}：${item.text}` }}</span>
              <a-icon type="close" style="float: right" />
            </span>
          </div>
        </div>
        <div style="overflow-y: scroll; flex: 1; padding: 0">
          <div class="uni-card" style="background: #fff">
            <a-form-model ref="ruleForm" layout="vertical" :model="filterForm">
              <a-form-model-item label="生产状态">
                <a-select mode="multiple" placeholder="请选择" v-model="filterForm.status" allowClear>
                  <a-select-option v-for="item in statusList" :key="item.value" :value="item.value">
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="工单编号">
                <a-input v-model="filterForm.orderCode" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="产品编号">
                <a-input v-model="filterForm.goodsCode" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="产品名称">
                <a-input v-model="filterForm.goodsName" placeholder="请输入" />
              </a-form-model-item>
                 <a-form-model-item label="规格">
                <a-input v-model="filterForm.goodsSpec" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="类型">
                <a-select
                  mode="multiple"
                  placeholder="请选择"
                  allowClear
                  style="width: 100%"
                  v-model="filterForm.goodsType"
                >
                  <a-select-option v-for="(item, i) in typeList" :key="i" :value="item.value">{{
                    item.text
                  }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="计划完成日期">
                <a-range-picker
                  :allowClear="true"
                  v-model="dateForm['planEndTime']"
                  style="width: 100%"
                  :disabled-date="disabledDate"
                  @change="(v) => onOk(v)"
                />
              </a-form-model-item>
            </a-form-model>
          </div>
        </div>
        <div class="footer-submit">
          <a-button class="margin-btn" @click="resetFilter">重置</a-button>
          <a-button type="primary" @click="handleFilter">确定</a-button>
        </div>
      </div>
    </a-drawer>
    <!-- 全选/分页 -->
    <div
      class="uni-card"
      :style="{
        position: 'fixed',
        bottom: 0,
        left: 0,
        zIndex: 2,
        width: '100%',
        background: '#fff',
        padding: '24px',
      }"
    >
      <div style="display: inline-block; margin-left: 242px">
        <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
        <span style="margin-left: 8px">
          {{ `已选 ${selectedRowKeys.length}/${total} 项` }}
          <span @click="clearArr" class="pubColor" style="margin: 0 10px">清空</span>
        </span>
      </div>
      <div style="display: inline-block; float: right">
        <a-pagination
          :total="total"
          v-model="current"
          :page-size-options="pageSizeOptions"
          :page-size="pageSize"
          @change="onChangePage"
          @showSizeChange="onShowSizeChange"
          show-quick-jumper
          show-size-changer
        />
      </div>
    </div>
    <a-modal style="width: 50%" v-model="selectExportVisiable" title="导出">
      <template slot="footer">
        <a-button key="back" @click="handleExportAll"> 导出全部数据 </a-button>
        <a-button key="submit" type="primary" @click="handleSelectExport"> 导出选中数据 </a-button>
      </template>
      {{ selectExportTitle }}
    </a-modal>
    <workOrderDetail ref="workOrderDetail"></workOrderDetail>
  </div>
</template>
<script>
import SetColumn from '@/pubComponent/SetColumn.vue'
import crumbs from '@/components/crumbs.vue'
import { getNewColumns, subStrText, commafyTofixed } from '@/utils/util'
import { getDictModel } from '@/api/goodsManagement'
import { API } from '@/api/requestFzs'
import moment from 'dayjs'
import { downFilePost } from '@/api/manage'
import { mapState } from 'vuex'
import tableDragResize from '@/mixins/tableDragResize'
// 表头
const columnsValue = [
  {
    title: '工单编号',
    width: 180,
    ellipsis: true,
    dataIndex: 'orderCode',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'orderCode',
    },
  },
  {
    title: '产品编号',
    dataIndex: 'goodsCode',
    width: 180,
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'goodsCode',
    },
  },
  {
    title: '产品名称',
    dataIndex: 'goodsName',
    ellipsis: true,
    width: 100,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'goodsName',
    },
  },
  {
    title: '规格',
    width: 100,
    ellipsis: true,
    dataIndex: 'goodsSpec',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'goodsSpec',
    },
  },
  {
    title: '类型',
    width: 100,
    ellipsis: true,
    dataIndex: 'goodsTypeText',
    searchKey: 'goodsType',
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'goodsTypeText',
    },
  },
  {
    title: '计划完成时间',
    width: 188,
    ellipsis: true,
    sorter: true,
    dataIndex: 'planEndTime',
    scopedSlots: { customRender: 'planEndTime' },
  },
  {
    title: '生产数量',
    width: 100,
    ellipsis: true,
    sorter: true,
    dataIndex: 'producedNum',
  },
    {
    title: '生产状态',
    width: 100,
    ellipsis: true,
    dataIndex: 'statusName',
    searchKey: 'status',
    scopedSlots: {
      filterDropdown: 'selectDropdownStatus',
      filterIcon: 'selectIcon',
      customRender: 'statusName',
    },
  },
  {
    title: '逾期天数',
    width: 100,
    ellipsis: true,
    sorter: true,
    dataIndex: 'overdueDay',
    scopedSlots: { customRender: 'overdueDay' },
  },
  {
    title: '逾期原因',
    width: 150,
    dataIndex: 'overdueReason',
    ellipsis: true,
    scopedSlots: { customRender: 'overdueReason' },
  },
]
let startDate = moment().startOf('month').format('YYYY-MM-DD HH:mm:ss')
let endDate = moment().format('YYYY-MM-DD HH:mm:ss')
export default {
  mixins: [tableDragResize],
  data() {
    return {
      selectExportTitle: '',
      reasonVisibles: false, // 逾期原因弹窗
      selectExportVisiable: false, // 导出弹窗
      selectExportParam: {}, // 导出参数
      filedKeys: '', // 导出字段
      fileName: '', // 导出文件名
      // 头部配置
      topArray: [
        {
          title: '待发货商品种类',
          number: '0',
        },
        {
          title: '待发货商品总数',
          number: '0',
        },
        {
          title: '待发货合同数',
          number: '0',
        },
        {
          title: '待发货客户数',
          number: '0',
        },
      ],
        statusList: [
        {
          label: '未开始',
          value: 'notStarted',
        },
        {
          label: '生产中',
          value: 'inProduction',
        },
        // {
        //   label: '已作废',
        //   value: 'abolished',
        // },
        {
          label: '已完成',
          value: 'completed',
        },
      ],
      commafyTofixed,
      moment,
      selectedRowKeys: [],
      selectedRows: [],
      subStrText,
      showFilter: false, // 筛选抽屉
      modelList: [], // 列表数据
      showSetColumn: false, // 显示
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      current: 1,
      total: 0,
      pageSize: 10,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      columnsValue,
      columns: [
        {
          title: '工单编号',
          width: 180,
          ellipsis: true,
          dataIndex: 'orderCode',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'orderCode',
          },
        },
        {
          title: '产品编号',
          dataIndex: 'goodsCode',
          width: 180,
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsCode',
          },
        },
        {
          title: '产品名称',
          dataIndex: 'goodsName',
          ellipsis: true,
          width: 100,
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsName',
          },
        },
        {
          title: '规格',
          width: 100,
          ellipsis: true,
          dataIndex: 'goodsSpec',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsSpec',
          },
        },
        {
          title: '类型',
          width: 100,
          ellipsis: true,
          dataIndex: 'goodsTypeText',
          searchKey: 'goodsType',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'goodsTypeText',
          },
        },
        {
          title: '计划完成时间',
          width: 188,
          ellipsis: true,
          sorter: true,
          dataIndex: 'planEndTime',
          scopedSlots: { customRender: 'planEndTime' },
        },
        {
          title: '生产数量',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'producedNum',
        },
        {
        title: '生产状态',
        width: 100,
        ellipsis: true,
        dataIndex: 'statusName',
        searchKey: 'status',
        scopedSlots: {
          filterDropdown: 'selectDropdownStatus',
          filterIcon: 'selectIcon',
          customRender: 'statusName',
        },
        },
        {
          title: '逾期天数',
          width: 100,
          ellipsis: true,
          sorter: true,
          dataIndex: 'overdueDay',
        },
        {
          title: '逾期原因',
          width: 150,
          dataIndex: 'overdueReason',
          ellipsis: true,
          scopedSlots: { customRender: 'overdueReason' },
        },
      ],
      filterForm: {
        orderCode: '',
        goodsCode: '',
        goodsName: '',
        goodsType: undefined,
        status:['notStarted','inProduction'],
        planEndTime: '',
        planEndTimeBegin: startDate,
        planEndTimeEnd: endDate,
      },
      filteredFormLable: {
        orderCode: '工单编号',
        goodsCode: '产品编号',
        goodsName: '产品名称',
        goodsType: '类型',
        status:'状态',
        planEndTime: '计划完成日期',
        goodsSpec:'规格',
      },
      sortForm: {
        sortType: '',
        sortColumn: '',
      },
      dateForm: {
        planEndTime: [startDate, endDate],
      } /* 筛选日期绑定对象 */,
      barNames: [],
      barNums: [],
      typeList: [],
      reasonColumns: [
        {
          title: '序号',
          width: 80,
          scopedSlots: { customRender: 'serialNo' },
        },
        {
          title: '逾期原因',
          scopedSlots: { customRender: 'overdueReason' },
        },
        {
          title: '操作',
          width: 80,
          scopedSlots: { customRender: 'actions' },
        },
      ],
      reasonList: [],
      reasonListCopy: [],
      loadingTable: false,
      isLoad: false,
      barRequests: {},
      pieRequests: {},
      tableKey: 1.9
    }
  },
  components: {
    SetColumn,
    crumbs,
    workOrderDetail: (resolve) => require(['@/views/workManagement/workOrder/workOrderDetail'], resolve)
  },
  computed: {
    ...mapState({
      collapsed: (state) => state.user.collapsed,
    }),
    filteredList() {
      let list = []
      for (let key in this.filterForm) {
        if (key == 'planEndTime') {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm.planEndTimeBegin
              ? moment(this.filterForm.planEndTimeBegin).format('YYYY-MM-DD') +
                '-' +
                moment(this.filterForm.planEndTimeEnd).format('YYYY-MM-DD')
              : '',
            key,
          })
        } else if (key == 'planEndTimeBegin' || key == 'planEndTimeEnd') {
        } else if (key == 'goodsType' && this.filterForm[key]) {
          let arr = []
          for (let i = 0; i < this.filterForm[key].length; i++) {
            const item = this.filterForm[key][i]
            for (let j = 0; j < this.typeList.length; j++) {
              const type = this.typeList[j]
              if (item == type.value) {
                arr.push(type.text)
              }
            }
          }
          list.push({
            title: this.filteredFormLable[key],
            text: arr.join(','),
            key,
          })
        } else if (key == 'status') {
          let strArr = ''
          for (let item of this.filterForm[key]) {
            for (let each of this.statusList) {
              if (item == each.value) {
                strArr += each.label + '，'
              }
            }
          }
          if (strArr) {
            strArr = strArr.substring(0, strArr.length - 1)
          }
          list.push({
            title: this.filteredFormLable[key],
            text: strArr,
            key,
          })
        } else {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm[key],
            key,
          })
        }
      }
      return list
    },
    filteredNums() {
      let nums = 0
      for (let key in this.filterForm) {
        if (this.filterForm[key] != '' && this.filterForm[key] != null && this.filterForm[key] != undefined) {
          nums += 1
          if (key == 'planEndTimeBegin') {
            nums -= 1
          }
        }
      }
      return nums
    },
    scrollX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum
    },
  },
  created() {
    this.initData()
    this.requestData()
  },
  mounted() {
    let parameter = {
      pageNo: this.current,
      pageSize: this.pageSize,
      ...this.filterForm,
      ...this.sortForm,
    }
    if(parameter.status){
      parameter.status = parameter.status.join(",");
    }
    // 过滤空值
    for (let key in parameter) {
      if (!parameter[key]) {
        delete parameter[key]
      }
    }
    this.getBarData(parameter)
    this.getPieData(parameter)
  },
  methods: {
    // 日期选择限制，未来日期不可选
    disabledDate(current) {
      let nowMon = new Date()
      if (moment(nowMon).isBefore(moment(current))) {
        return true
      }
      return false
    },
    refresh() {
      let parameter = {
        pageNo: this.current,
        pageSize: this.pageSize,
        ...this.filterForm,
        ...this.sortForm,
      }
      if (parameter.goodsType) {
        parameter.goodsType = parameter.goodsType.join(',')
      }
      if (parameter.status) {
        parameter.status = parameter.status.join(',')
      }
      // 过滤空值
      for (let key in parameter) {
        if (!parameter[key]) {
          delete parameter[key]
        }
      }
      this.getPieData(parameter)
    },
    changeReason(e, r) {
      this.loadingTable = true
      API.messProductOrderEdit({
        id: r.id,
        overdueReasonId: e,
      })
        .then((res) => {
          this.loadingTable = false
        })
        .catch((err) => {
          this.loadingTable = false
        })
    },
    reasonShow() {
      this.reasonListCopy = JSON.parse(JSON.stringify(this.reasonList))
      this.reasonVisibles = true
    },
    delReason(v, i) {
      this.reasonList.splice(i, 1)
    },
    addReason() {
      if (this.reasonList.length === 10) {
        this.$antdMessage.info('最多添加十条逾期原因')
        return
      }
      this.reasonList.push({
        overdueReason: '',
        serialNo: this.reasonList.length + 1,
        id: '',
      })
    },
    // 确定配置逾期原因
    handleOk() {
      API.messProductOverdueReasonAdd(this.reasonList).then((res) => {
        if (res.code == 200) {
          this.reasonVisibles = false
          this.$antdMessage.success('逾期原因配置成功！')
          this.getReasonList()
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    // 取消配置逾期原因
    cancelReason() {
      this.reasonList = JSON.parse(JSON.stringify(this.reasonListCopy))
      this.reasonVisibles = false
    },
    // 请求柱状图数据
    getBarData(parameter) {
      this.isLoad = true
      API.getOverdueOrderHistogram(parameter).then((res) => {
        if (res.result) {
          this.barRequests = res.result
          this.drawChartBar(res.result)
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    // 请求环形图数据
    getPieData(parameter) {
      API.getOverdueOrderPieChart(parameter).then((res) => {
        if (res.result) {
          let list = res.result
          let names = []
          list.sort((a, b) => {
            return b.rate - a.rate
          })
          list.forEach((item) => {
            item.value = item.rate
            names.push(item.name)
          })
          let data = {
            list,
            names,
          }
          this.pieRequests = data
          this.drawChartPie(data)
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    // 柱状图实例
    drawChartBar(data) {
      let that = this
      let myChart = this.$echarts.init(document.getElementById('barchart'), null, { renderer: 'svg' })
      let option = {
        title: {
          text: `逾期工单数：${data.totalOrderNum}`,
        },
        tooltip: {},
        xAxis: {
          data: data.goodsName,
          axisLabel: {
        formatter: val => {
          let txt = val
          if (val.length > 3) {
            txt = val.substr(0, 3) + '...'
          }
          return txt
        }
      }
        },
        yAxis: {},
        series: [
          {
            name: '物品名称',
            type: 'bar',
            data: data.orderNum,
          },
        ],
        grid: {
          left: '24px',
          right: '24px',
          bottom: '20px',
        },
        itemStyle: {
          color: '#1890FF',
        },
        formatter: function (params) {
          let name = that.barRequests.goodsName[params.dataIndex]
          let num = that.barRequests.orderNum[params.dataIndex]
          return (
            name +
            '<br/>' +
            '<span style="display:inline-block;height:10px;width:10px;border-radius:50%;background:#1890FF;margin-right:5px"></span>' +
            '数量：' +
            num
          )
        },
      }
      myChart.setOption(option)
    },
    // 环形图实例
    drawChartPie(data) {
      let that = this
      let myChart = this.$echarts.init(document.getElementById('piechart'), null, { renderer: 'svg' })
      let option = {
        title: {
          text: '逾期原因分布',
          x: '24px',
          y: '0px',
        },
        legend: {
          // orient 设置布局方式，默认水平布局，可选值：'horizontal'（水平） ¦ 'vertical'（垂直）
          orient: 'vertical',
          left: '65%', //图例距离左的距离
          top: '10%',
          itemWidth: 24, // 设置图例图形的宽
          itemHeight: 18, // 设置图例图形的高
          textStyle: {
            color: '#666', // 图例文字颜色
          },
          data: data.names,
          formatter: function (v) {
            console.log('vvvv', v)
            if (!v) return '-'
            if (v.length > 6) {
              v = v.slice(0, 6) + '...'
              return v
            } else {
              return v
            }
          },
        },
        tooltip: {
          trigger: 'item',
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['30%', '60%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            // emphasis: {
            //   label: {
            //     show: true,
            //     fontSize: '14',
            //     fontWeight: 'bold'
            //   }
            // },
            labelLine: {
              show: false,
            },
            data: data.list,
          },
        ],
        formatter: function (params) {
          let name = that.pieRequests.names[params.dataIndex]
          let rate = that.pieRequests.list[params.dataIndex].rate
          let num = that.pieRequests.list[params.dataIndex].num
          return name + '<br/>' + '占比：' + rate + '<br/>' + '数量：' + num
        },
      }
      myChart.setOption(option)
    },
    // 导出
    handleExport(e) {
      let that = this
      // 获取动态列
      let filedKeysList = []
      that.columns.forEach((keys) => {
        filedKeysList.push(keys.dataIndex)
      })
      // filedKeysList.pop()//删除最后一个的操作列
      that.filedKeys = filedKeysList.join(',')
      //设置文件名
      that.fileName = `${
        that.filterForm.planEndTimeBegin
          ? moment(that.filterForm.planEndTimeBegin).format('YYYY-MM-DD') +
            '-' +
            moment(that.filterForm.planEndTimeEnd).format('YYYY-MM-DD') +
            '逾期统计'
          : '逾期统计'
      }`
      if (!e || e.length === 0) {
        that.handleExportAll()
        that.selectExportVisiable = false
      } else {
        that.selectExportTitle = `已选中${e.length}条数据`
        that.selectExportVisiable = true
        that.selectExportParam = {
          selectedList: e,
          fileName: that.fileName, //文件名
          filedKeys: that.filedKeys, //动态列
        }
      }
    },
    handleSelectExport() {
      this.selectExportVisiable = false
      downFilePost('/mess/messProductReport/exportOverdueStatisticsXls', this.selectExportParam).then((data) => {
        if (data.type == 'application/json') {
          const reader = new FileReader() //创建一个FileReader实例
          reader.readAsText(data, 'utf-8') //读取文件,结果用字符串形式表示
          reader.onload = function () {
            //读取完成后,**获取reader.result**
            const msg = JSON.parse(reader.result)
            this.$antdMessage.error(msg.message) //弹出错误提示
          }
          return
        }
        if (!data) {
          this.$antdMessage.error('导出失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), this.fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', this.fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    handleExportAll() {
      let that = this
      that.$antdConfirm({
        title: `确定导出全部数据?`,
        onOk() {
          let param = {
            ...that.filterForm,
            ...that.sortForm,
            fileName: that.fileName,
            filedKeys: that.filedKeys,
          }
          if (param.goodsType) {
            param.goodsType = param.goodsType.join(',')
          }
          if (param.status) {
            param.status = param.status.join(',')
          }
          for (let key in param) {
            if (!!param[key] || param[key] === 0) {
              // nothing
            } else {
              delete param[key]
            }
          }
          console.log(param, '导出选中数据param')
          downFilePost('/mess/messProductReport/exportOverdueStatisticsXls', param).then((data) => {
            if (data.type == 'application/json') {
              const reader = new FileReader() //创建一个FileReader实例
              reader.readAsText(data, 'utf-8') //读取文件,结果用字符串形式表示
              reader.onload = function () {
                //读取完成后,**获取reader.result**
                const msg = JSON.parse(reader.result)
                that.$antdMessage.error(msg.message) //弹出错误提示
              }
              return
            }
            if (!data) {
              this.$antdMessage.error('导出失败')
              that.selectExportVisiable = false
              return
            }
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
              window.navigator.msSaveBlob(new Blob([data]), that.fileName + '.xls')
              that.selectExportVisiable = false
            } else {
              let url = window.URL.createObjectURL(new Blob([data]))
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', that.fileName + '.xls')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link) //下载完成移除元素
              window.URL.revokeObjectURL(url) //释放掉blob对象
              that.selectExportVisiable = false
            }
          })
        },
        onCancel() {},
      })
    },
    /* 出入库日期选择 */
    onOk(value) {
      if (value.length == 0) {
        this.filterForm[`planEndTimeBegin`] = ''
        this.filterForm[`planEndTimeEnd`] = ''
        this.filterForm['planEndTime'] = ''
        this.handleSearch()
        return
      }
      this.filterForm[`planEndTimeBegin`] = moment(value[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.filterForm[`planEndTimeEnd`] = moment(value[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.handleSearch()
    },
    // 排序
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      if (sorter.order) {
        let sortType = ''
        if (sorter.order == 'ascend') {
          sortType = 'ASC'
        } else {
          sortType = 'DESC'
        }
        this.sortForm = {
          sortType: sortType,
          sortColumn: sorter.columnKey,
        }
        this.requestData()
      } else {
        this.sortForm = {
          sortType: '',
          sortColumn: '',
        }
        this.requestData()
      }
    },
    // table选择
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.checkBoxStatus()
    },
    // 全选
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.selectedRowKeys.push(item.id)
          this.selectedRows = this.selectedRows.filter((each) => {
            return each.id != item.id
          })
          this.selectedRows.push(item)
        }
      } else {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.selectedRows = this.selectedRows.filter((each) => {
            return each.id != item.id
          })
        }
      }
      this.checkBoxStatus()
    },
    // 清空
    clearArr() {
      this.selectedRowKeys = []
      this.selectedRows = []
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.modelList) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 分页
    onChangePage(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData(true)
    },
    onShowSizeChange(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData(true)
    },
    handleSearch(selectedKeys, confirm, dataIndex, clearFilters) {
      this.current = 1
      this.requestData()
    },
    /* 打开筛选 */
    handleShowFilter() {
      this.showFilter = true
    },
    /* 关闭筛选 */
    closeFilter() {
      this.showFilter = false
    },
    /* 确定筛选 */
    handleFilter() {
      this.handleSearch()
      this.showFilter = false
    },
    /* 删除已选 */
    delFiltered(key) {
      if (key == 'planEndTime') {
        this.filterForm.planEndTimeBegin = ''
        this.filterForm.planEndTimeEnd = ''
        this.filterForm[key] = ''
        this.dateForm[key] = null
      } else if (key == 'goodsType') {
        this.filterForm[key] = undefined
      } else if (key == 'status') {
        this.filterForm[key] = []
      }else {
        this.filterForm[key] = ''
      }
    },
    /* 重置筛选 */
    resetFilter() {
      this.filterForm = {
        orderCode: '',
        goodsCode: '',
        goodsName: '',
        goodsSpec:'',
        goodsType: undefined,
        status:[],
        planEndTime: '',
        planEndTimeBegin: '',
        planEndTimeEnd: '',
      }
      
      this.dateForm = {}
      this.handleSearch()
    },
    /* 初始/加载设置列 */
    initData() {
      var oldValue = localStorage.getItem(this.BUSI_CONST.Entity.OVERDUE_STATISTICS)
      this.columns = getNewColumns(this.columnsValue, JSON.parse(oldValue), [], this.columns)
      let parameters = { dictCode: 'wms_goods_type' }
      getDictModel(parameters).then((res) => {
        if (res.code == 200) {
          this.typeList = res.result
        }
      })
      this.getReasonList()
    },
    getReasonList() {
      API.messProductOverdueReasonList({
        pageNo: 1,
        pageSize: 10,
      }).then((res) => {
        if (res.code == 200) {
          this.reasonList = res.result.records
        }
      })
    },
    /* 请求列表数据 */
    requestData(check) {
      let parameter = {
        pageNo: this.current,
        pageSize: this.pageSize,
        ...this.filterForm,
        ...this.sortForm,
      }
      if (parameter.goodsType) {
        parameter.goodsType = parameter.goodsType.join(',')
      }
      if (parameter.status) {
        parameter.status = parameter.status.join(',')
      }
      // 过滤空值
      for (let key in parameter) {
        if (!parameter[key]) {
          delete parameter[key]
        }
      }
      if (this.isLoad) {
        this.getBarData(parameter)
        this.getPieData(parameter)
      }
      API.getOverdueStatisticsList(parameter).then((res) => {
        if (res.code == 200) {
          if (res.result.total) {
            this.total = res.result.total
          } else {
            this.total = 0
          }
          let mods = res.result.records
          mods.forEach((mod) => {
            if (!mod.overdueReasonId) {
              mod.overdueReasonId = undefined
            }
          })
          this.modelList = mods
          if (check) {
            this.checkBoxStatus()
          }
        }
      })
    },
    /* 打开设置列面板 */
    showColumn() {
      this.showSetColumn = true
      this.$nextTick(() => {
        this.$refs.SetColumn.paramsData(this.columnsValue, this.BUSI_CONST.Entity.OVERDUE_STATISTICS, this.columns)
      })
    },
    /* 设置列 */
    sureBtn(emitArr) {
      this.columns = getNewColumns(this.columnsValue, emitArr, [])
      console.log(this.columns)
      localStorage.setItem(this.BUSI_CONST.Entity.OVERDUE_STATISTICS, JSON.stringify(emitArr))
      this.tableKey += 1
    },
    /* 详情 */
    handleDetail(id, path, from) {
      this.$refs.workOrderDetail.initDetail({id, from})
      // this.$openWay(this, true, path, { id, from })
    },
    //点击返回按钮
    goBack() {
      console.log('goback')
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
// @import '~@assets/less/common.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
.header {
  width: 150%;
  margin: -12px -12px @distance4;
}
.backBox {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .backC {
    cursor: pointer;
    display: flex;
    align-items: center;
  }
}
.j-table-force-nowrap {
  margin-top: @distance1;
}
.btns {
  margin-left: @distance5;
}
.right-btn {
  float: right;
  display: flex;
  justify-content: flex-end;
}
.mg-left {
  margin-left: @distance3;
}
.filter-tit {
  background: #fff;
  border-bottom: 1px solid @greyBorder;
  font-size: @fontSize4;
}
.filter-num {
  color: @normalFont;
}
.filter-body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.margin-btn {
  margin-right: @distance5;
}
.filter-tag {
  display: inline-block;
  position: relative;
  padding: 8px 10px;
  border-radius: 4px;
  font-size: @fontSize1;
  line-height: @fontSize1;
  max-width: 100%;
  background: @greyBg;
  color: @titFont;
  cursor: pointer;
  .tag-text {
    display: inline-block;
    padding-right: 20px;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .anticon-close {
    position: absolute;
    right: 8px;
    top: 8px;
  }
}
.tag-wrap:nth-of-type(n + 2) {
  margin-top: 10px;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
// /deep/ .ant-card-body {
//   height: calc(100vh - 214px);
//   overflow: hidden;
//   padding: 20px 16px;
// }
.pubColor {
  font-size: 14px;
  color: #1890ff;
  cursor: pointer;
}

div.topBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  background: #fff;
  div.itemBox {
    display: flex;
    justify-content: center;
    align-items: center;
    flex: 1;
    box-sizing: border-box;
    height: 44px;
    position: relative;
    border-right: 1px solid #eeeeee;

    div.rightBox {
      text-align: center;
      height: 44px;
      cursor: pointer;
      display: flex;
      align-items: flex-start;
      flex-direction: column;
      justify-content: flex-start;
      margin-left: 16px;
      div.rightTop {
        font-size: 24px;
        color: #191f25;
        line-height: 24px;
        margin-top: 12px;
      }

      div.rightBot {
        font-size: 14px;
        color: #888888;
      }
    }
  }
}
.topBox .itemBox:last-child {
  border: none;
}
.topSearch {
  padding: 0 0 10px 38px;
}
/deep/.ant-table-placeholder {
  padding: 0;
  .ant-empty-normal {
    margin: 0;
  }
}
</style>
